package com.gitee.mrj.aiboot.core.sf.generators.ui;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.KVS;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.SFRender;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SFRenderGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        SFRender render = AnnotatedElementUtils.findMergedAnnotation(field, SFRender.class);
        ObjectNode ui = node.getUi();

        putString(ui, "widget", render.widget());
        String[] clazz = render.clazz();
        if (ArrayUtils.isNotEmpty(clazz)) {
            ArrayNode clazz1 = putArray(ui, "clazz");
            for (String c : clazz) {
                clazz1.add(c);
            }
        }
        putString(ui, "size", render.size().value());
        putInt(ui, "width", render.width());
        putString(ui, "optional", render.optional());
        putString(ui, "optionalHelp", render.optionalHelp());
        if (render.debug()) {
            ui.put("debug", render.debug());
        }
        if (render.hidden()) {
            ui.put("hidden", render.hidden());
        }

        KVS[] kvs = render.visibleIf();
        if (ArrayUtils.isNotEmpty(kvs)) {
            ArrayNode overlayStyle = putArray(ui, "visibleIf");
            for (KVS kv : kvs) {
                ArrayNode array = overlayStyle.addObject().putArray(kv.key());
                for (String s : kv.value()) {
                    array.add(s);
                }

            }
        }


    }

    @Override
    public void generate(UIForm root, Class clazz) {
        SFRender render = AnnotatedElementUtils.findMergedAnnotation(clazz, SFRender.class);
        ObjectNode ui = root.getUi();
        putString(ui, "size", render.size().value());

        if (render.debug()) {
            ui.put("debug", render.debug());
        }

        KVS[] kvs = render.visibleIf();
        if (ArrayUtils.isNotEmpty(kvs)) {
            ArrayNode overlayStyle = putArray(ui, "visibleIf");
            for (KVS kv : kvs) {
                ArrayNode array = overlayStyle.addObject().putArray(kv.key());
                for (String s : kv.value()) {
                    array.add(s);
                }

            }
        }
    }

    @Override
    public Class[] supports() {
        return new Class[]{SFRender.class};
    }
}
